package com.nlscan.qdkit.ui.publico.util;

import android.content.Context;
import android.text.TextUtils;

import com.nlscan.qdkit.ui.publico.config.PublicoConfig;
import com.quvii.qvlib.util.QvEncryptKeyStoreUtil;
import com.quvii.qvlib.util.QvSpUtil;

import java.util.UUID;

/**
 * SharePrefs
 * -- 1. 敏感数据加密
 */
public class SpUtil extends QvSpUtil {

    private SpUtil() {
    }

    public static SpUtil getInstance(Context context) {
        return SingletonHolder.instance;
    }

    public static SpUtil getInstance() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static final SpUtil instance = new SpUtil();
    }

    private static final String USER_NAME = "user_name";
    private static final String PASSWORD = "password";
    private static final String EMAIL = "email";
    private static final String ACCOUNT = "account";
    private static final String PREVIEW_CHANNEL_MAP = "_preview_channel_map";
    private static final String NEED_AUDIO_MAP = "_need_audio_map";
    private static final String WINDOW_NUM = "_window_num";
    private static final String IS_STOP_ALL = "_is_stop_all";

    private static final String SCREEN_LONG_SIDE_LENGTH = "SLSL";
    private static final String SCREEN_SHORT_SIDE_LENGTH = "SSSL";

    // TODO: 2019/7/15 临时处理，之后放到DB中

    private static final String PREVIEW_STREAM = "_preview_stream";
    private static final String PLAYBACK_STREAM = "_playback_stream";

    public static final String NET_CHANGE_TIP = "net_change_tip";

    /**
     * 是否已经添加了demo设备
     */
    private static final String HAS_DEMO_DEV = "has_add_demo_dev";

    // 上一次服务器地址
    private static final String LAST_SERVER_ADDRESS = "last_server_address";

    // 设备唯一标识
    private static final String UNIQUE_ID = "unique_id";

    // 是否已经初始化通知渠道
    private static final String HAS_INIT_NOTIFICATION_CHANNEL = "has_init_notification_channel";

    // 是否为调试模式
    private static final String IS_DEBUG_MODE = "is_debug_mode";

    private static final String APP_AUTH_MODE = "aam";

    private static final String APP_SERVICE_IP = "API";
    private static final String APP_SERVICE_PORT = "APP";
    private static final String APP_DEBUG_MODE = "adm";

    private static final String HS_SERVER_ADDRESS = "hs_server_address";

    private static final String MOBILE_NETWORK_TIP = "mobile_network_tip";
    private static final String APP_DEVICE_CONFIG_PICTURE_URL = "adcpu";
    private static final String APP_DEVICE_CONFIG_VERSION = "adcv";

    private static final String SSID_INFO = "si_";
    private static final String APP_IS_SAVE_ROUTER_PASSWORD = "aisrp";

    /**
     * -- 是否是首次覆盖安装
     * -- 1. 覆盖QvHome 010QV199 覆盖安装免登录版本的QvHome
     * -- 2. 覆盖QvFun  050QV113 覆盖登陆版本QvFun
     * -- 3. 覆盖v1.2_vEyePro    账户信息由sp改为db
     */
    private static final String IS_FIRST_COVER_INSTALL = "ifciq";

    private static final String COVER_QVFUN_USERNAME = "username";
    private static final String LOGIN_TYPE = "loginType";
    private static final String COUNTRY_CODE = "countryCode";

    private static final String IS_PAD_MODE = "is_pad_mode";

    private static final String IS_USE_PERSIAN_CALENDAR = "isUsePersianCalendar";
    private static final String IS_SUPPORT_SUB_SHARE = "isSupportSubShare";

    private static final String KEY_CURRENT_LOGIN_ACCOUNT_ID = "kcla";

    private static final String DEVICE_DEFAULT_SHARE_PERMISSION = "DDS_permission";
    private static final String DEVICE_DEFAULT_SHARE_PERIODS = "DDS_periods";
    private static final String DEVICE_DEFAULT_SHARE_WEEKDAYS = "DDS_weekdays";

    private static final String IP_ADD_VSU_MODE = "IAVM";

    /************************************
     * 加密value BEGIN
     ************************************/

    public void setAppServiceIp(String ip) {
        setEncryptValue(APP_SERVICE_IP, ip);
    }

    public String getAppServiceIp() {
        return getEncryptValue(APP_SERVICE_IP);
    }

    public void setAppServicePort(int port) {
        setIntValue(APP_SERVICE_PORT, port);
    }

    public int getAppServicePort() {
        return getIntValue(APP_SERVICE_PORT);
    }

    public String getUserName() {
        return getEncryptValue(USER_NAME);
    }

    public String getEmail() {
        return getEncryptValue(EMAIL);
    }

    public void setEmail(String email) {
        setEncryptValue(EMAIL, email);
    }

    public String getAccount() {
        return getEncryptValue(ACCOUNT);
    }

    public void setAccount(String email) {
        setEncryptValue(ACCOUNT, email);
    }

    public String getPassword() {
        return getEncryptValue(PASSWORD);
    }

    public void setPassword(String password) {
        setEncryptValue(PASSWORD, password);
    }


    public String getLastServerAddress() {
        return getEncryptValue(LAST_SERVER_ADDRESS);
    }

    public void setLastServerAddress(String lastServerAddress) {
        setEncryptValue(LAST_SERVER_ADDRESS, lastServerAddress);
    }

    public String getUniqueId() {
        String uniqueId = SpUtil.getInstance().getEncryptValue(UNIQUE_ID);
        if (TextUtils.isEmpty(uniqueId)) {
            uniqueId = generateUniqueId();
            SpUtil.getInstance().setEncryptValue(UNIQUE_ID, uniqueId);
        }
        return uniqueId;
    }

    //获取手机唯一标志号,根据硬件信息生成

    /**
     * 改用UUID来作为唯一标识码
     * -- 尝试解决google的不安全加密警告
     *
     * @return
     */
    private String generateUniqueId() {
//        String id = null;
//        try {
//            id = Settings.Secure.getString(
//                    context.getContentResolver(),
//                    android.provider.Settings.Secure.ANDROID_ID);
//        } catch (Exception e) {
//            LogUtil.e(e.toString());
//        }
//        return TextUtils.isEmpty(id) ? UUID.randomUUID().toString() : id;
        return UUID.randomUUID().toString();
    }

    public void setServiceId(String id) {
        setEncryptValue("ServiceId", id);
    }

    public String getServiceId() {
        return getEncryptValue("ServiceId");
    }

    public void setHsServerAddress(String serverAddress) {
        setEncryptValue(HS_SERVER_ADDRESS, serverAddress);
    }

    public String getHsServerAddress() {
        return getEncryptValue(HS_SERVER_ADDRESS);
    }


    /************************************
     * 加密value END
     ************************************/






    // ------------------------------------------------用户资料----------------------------------------------

    /*是否需要版本更新begin*/
    public boolean getIsNeedVersionUpdate() {
        return getBooleanValue("IsNeedVersionUpdate");
    }

    public void setIsNeedVersionUpdate(boolean IsNeedVersionUpdate) {
        setBooleanValue("IsNeedVersionUpdate", IsNeedVersionUpdate);
    }

    //获取下载的最新的版本信息
    public String getApkName() {
        return getValue("apkname");
    }

    public void setApkName(String apkname) {
        setValue("apkname", apkname);
    }

    public String getVersionName() {
        return getValue("versionname");
    }

    public void setVersionName(String versionname) {
        setValue("versionname", versionname);
    }

    public String getVersionTime() {
        return getValue("versiontime");
    }

    public void setVersionTime(String versiontime) {
        setValue("versiontime", versiontime);
    }

    public String getVersionFeature() {
        return getValue("versionfeature");
    }

    public void setVersionFeature(String versionfeature) {
        setValue("versionfeature", versionfeature);
    }

    public String getApkSize() {
        return getValue("apksize");
    }

    public void setApkSize(String apksize) {
        setValue("apksize", apksize);
    }

    public void setIsLogin(boolean isLogin) {
//        LogUtil.e("test==================> is login: " + isLogin);
//        LogUtil.trace("setIsLogin");
        setBooleanValue("isLogin", isLogin);
    }

    public boolean hasLogin() {
        return getBooleanValue("isLogin");
    }

    // 保存用户是否点击了“记住密码”
    public void setRememberPwd(boolean isChecked) {
        setBooleanValue("rpIsChecked", isChecked);
    }

    public boolean getRememberPwd() {
        return getBooleanValue("rpIsChecked");
    }

    /**
     * 判断是否为免登录
     */
    public boolean isLocalLogin() {
        return getBooleanValue("isLocalLogin");
    }

    public void setLocalLogin(boolean isLocalLogin) {
        setBooleanValue("isLocalLogin", isLocalLogin);
    }

    //判断用户是否设置了密码保护
    public void setPasswordProtect(boolean hasPasswordProtect) {
        setBooleanValue("hasPasswordProtect", hasPasswordProtect);
    }

    public boolean getPasswordProtect() {
        return getBooleanValue("hasPasswordProtect");
    }

    public void setPasswordProtectNumber(String passwordProtect) {
        setValue("passwordProtect", passwordProtect);
    }

    public String getPasswordProtectNumber() {
        return getValue("passwordProtect");
    }

    //保存云台步长的值
    public void setCloudStep(int cloudStep) {
        setIntValue("cloudStep", cloudStep);
    }

    public int getCloudStep() {
        int step = getIntValue("cloudStep");
        if (step <= 0) {
            step = 3;
        }
        return step;
    }

    //免打扰模式
    public void setVibration(boolean vibration) {
        setBooleanValue("vibration", vibration);
    }

    public boolean getVibration() {
        return getBooleanValue("vibration");
    }

    public void setNotificationSound(boolean notificationSound) {
        setBooleanValue("notificationSound", notificationSound);
    }

    public boolean getNotificationSound() {
        return getBooleanValue("notificationSound");
    }

    public void setSkipGuide(boolean skipGuide) {
        setBooleanValue("skipGuide", skipGuide);
    }

    public boolean getSkipGuide() {
        return getBooleanValue("skipGuide");
    }

    public void setAddDemoDevice(boolean isAdd) {
        setBooleanValue("sadd", isAdd);
    }

    public boolean isAddDemoDevice() {
        return getBooleanValue("sadd");
    }

    //记录云台步长界面中点击的位置x
    public void setCloudStepPosition(int position) {
        setIntValue("position", position);
    }

    @Deprecated
    public int getCloudStepPosition() {
        return getIntValue("position");
    }


    public void setNoDisturb(boolean noDisturb) {
        setBooleanValue("noDisturb", noDisturb);
    }

    public boolean getNoDisturb() {
        return getBooleanValue("noDisturb");
    }

//	//记录用户是否是自动登录状态
//	public void setIfAutoLog(boolean autoLog){
//		setBooleanValue("autoLog",autoLog );
//	}
//	public boolean getIfAutoLog(){
//		return getBooleanValue("autoLog");
//	}


    /*
        网络切换弹出提示
     */

    public boolean isNetChangedNoTip() {
        return getBooleanValue(NET_CHANGE_TIP);
    }

    public void setIsNetChangedNoTip(boolean flag) {
        setBooleanValue(NET_CHANGE_TIP, flag);
    }


    /**
     * 【019QV118】2018-2-8 免登录重新提供demo设备
     */

    public boolean getHasDemoDev() {
        return getBooleanValue(HAS_DEMO_DEV);
    }

    public void setHasDemoDev(boolean hasDemoDev) {
        setBooleanValue(HAS_DEMO_DEV, hasDemoDev);
    }

    public boolean getHasInitNotificationChannel() {
        return getBooleanValue(HAS_INIT_NOTIFICATION_CHANNEL);
    }

    public void setHasInitNotificationChannel(boolean hasInit) {
        setBooleanValue(HAS_INIT_NOTIFICATION_CHANNEL, hasInit);
    }

    public boolean isDebugMode() {
        return getBooleanValue(IS_DEBUG_MODE, PublicoConfig.debug);
    }

    public void setIsDebugMode(boolean enable) {
        setBooleanValue(IS_DEBUG_MODE, enable);
    }

//    public int getAppAuthMode() {
//        return getIntValue(APP_AUTH_MODE, SdkStatus.AUTH_MODE_USER_LOGIN);
//    }

    public void setAppAuthMode(int mode) {
        setIntValue(APP_AUTH_MODE, mode);
    }


    @Override
    protected String getSharePreferencesName() {
        return "config";
    }

    public void setMobileNetworkSwitchState(boolean mobileNetworkTip) {
        setBooleanValue(MOBILE_NETWORK_TIP, mobileNetworkTip);
    }

    public boolean getMobileNetworkSwitchState() {
        return getBooleanValue(MOBILE_NETWORK_TIP, true);
    }

    public String getAppDeviceConfigPictureUrl() {
        return getValue(APP_DEVICE_CONFIG_PICTURE_URL);
    }

    public void setAppDeviceConfigPictureUrl(String url) {
        setValue(APP_DEVICE_CONFIG_PICTURE_URL, url);
    }

    public void setAppDeviceConfigVersion(int version) {
        setIntValue(APP_DEVICE_CONFIG_VERSION, version);
    }

    public int getAppDeviceConfigVersion() {
        return getIntValue(APP_DEVICE_CONFIG_VERSION);
    }

    public void setSsidInfo(String ssid, String password) {
        setValue(QvEncryptKeyStoreUtil.encodeWithAes(SSID_INFO + ssid),
                QvEncryptKeyStoreUtil.encodeWithAes(password));
    }

    public String getSsidInfo(String ssid) {
        return QvEncryptKeyStoreUtil.decodeWithAes(getValue(QvEncryptKeyStoreUtil.encodeWithAes(SSID_INFO + ssid)));
    }

    public void removeSsidInfo(String ssid) {
        if (!TextUtils.isEmpty(getSsidInfo(ssid))) {
            remove(QvEncryptKeyStoreUtil.encodeWithAes(SSID_INFO + ssid));
        }
    }

    public void setAppIsSaveRouterPassword(boolean isSavePassword) {
        setBooleanValue(APP_IS_SAVE_ROUTER_PASSWORD, isSavePassword);
    }

    public boolean isAppIsSaveRouterPassword() {
        return getSP().getBoolean(APP_IS_SAVE_ROUTER_PASSWORD, true);
    }

    public int getScreenLongSideLength() {
        return getIntValue(SCREEN_LONG_SIDE_LENGTH);
    }

    public void setScreenLongSideLength(int length) {
        setIntValue(SCREEN_LONG_SIDE_LENGTH, length);
    }

    public int getScreenShortSideLength() {
        return getIntValue(SCREEN_SHORT_SIDE_LENGTH);
    }

    public void setScreenShortSideLength(int length) {
        setIntValue(SCREEN_SHORT_SIDE_LENGTH, length);
    }

    public void setIsFirstCoverInstall(boolean isFirst) {
        setBooleanValue(IS_FIRST_COVER_INSTALL, isFirst);
    }

    public boolean isFirstCoverInstall() {
        return getSP().getBoolean(IS_FIRST_COVER_INSTALL, true);
    }

    /**
     * 覆盖QvFun相关 BEGIN
     */

    public String getCoverQvFunUsername() {
        return getValue(COVER_QVFUN_USERNAME);
    }

    public String getLoginType() {
        return getValue(LOGIN_TYPE);
    }

    public String getCountryCode() {
        return getValue(COUNTRY_CODE);
    }

    /**
     * 覆盖SPC Smart
     * -- 老APP存在问题，AES key生成异常，导致没加密，但做了hash 处理
     */
    public String getEncryptPassword() {
        return getValue(PASSWORD);
    }

    public void removeFirstCoverInstallQvFunAccountData() {
        setValue(COVER_QVFUN_USERNAME, "");
        setValue(LOGIN_TYPE, "");
        setValue(COUNTRY_CODE, "");
        setValue(PASSWORD, "");
    }

    /**
     * 覆盖QvFun相关 END
     */


    public boolean isPadMode() {
        return getBooleanValue(IS_PAD_MODE);
    }

    public void setPadMode(boolean enable) {
        setBooleanValue(IS_PAD_MODE, enable);
    }


    public boolean isUsePersianCalendar(boolean defaultValue) {
        return getBooleanValue(IS_USE_PERSIAN_CALENDAR, defaultValue);
    }

    public void setUsePersianCalendar(boolean enable) {
        setBooleanValue(IS_USE_PERSIAN_CALENDAR, enable);
    }

    public boolean isSupportSubShare(boolean defaultValue) {
        return getBooleanValue(IS_SUPPORT_SUB_SHARE, defaultValue);
    }

    public void setSupportSubShare(boolean enable) {
        setBooleanValue(IS_SUPPORT_SUB_SHARE, enable);
    }

    public void setCurrentLoginAccountId(String id) {
        setEncryptValue(KEY_CURRENT_LOGIN_ACCOUNT_ID, id);
    }

    public String getCurrentLoginAccountId() {
        return getEncryptValue(KEY_CURRENT_LOGIN_ACCOUNT_ID);
    }

    public void setDeviceDefaultSharePeriods(String permission) {
        setValue(DEVICE_DEFAULT_SHARE_PERIODS, permission);
    }



    public void setDeviceDefaultShareWeekdays(String permission) {
        setValue(DEVICE_DEFAULT_SHARE_WEEKDAYS, permission);
    }

//    public int getIpAddVsuMode() {
//        return getIntValue(IP_ADD_VSU_MODE, PublicoConfig.IP_ADD_VSU_MODE);
//    }

    public void setIpAddVsuMode(int mode) {
        setIntValue(IP_ADD_VSU_MODE, mode);
    }

}
